'use client';
import ImageUpload from '@/components/admin/common/ImageUpload';
import PageTitle from '@/components/admin/common/PageTitle';
import SuperInput from '@/components/admin/common/SuperInput';
import SuperPasswordInput from '@/components/admin/common/SuperPasswordInput';
import Loading from '@/components/common/Loading';
import message from '@/components/common/message';
import { LOCAL_USER, EVENTBUS_USER_UPDATE, ROUTE_LOGIN } from '@/config/settings';
import React, { useEffect, useState } from 'react'
import eventBus from '@/utils/eventBus';
import isEqual from 'lodash/isEqual';
import { useRouter } from 'next/navigation';
import axios from 'axios';
import NProgress from 'nprogress'

export default function Settings() {
  const [loaded, setLoaded] = useState(false);
  const [originUserInfo, setOriginUserInfo] = useState({});
  const [userInfo, setUserInfo] = useState({});
  const [state, setState] = useState(false);
  const [isEdited, setIsEdited] = useState(false);
  const [isChangePassword, setIsChangePassword] = useState(false);
  const router = useRouter();

  useEffect(() => {
    if (localStorage.getItem(LOCAL_USER)) {
      const userInfo = JSON.parse(localStorage.getItem(LOCAL_USER));
      const newUserInfo = { ...userInfo, old_password: '', new_password: '' };
      setOriginUserInfo(newUserInfo);
      setUserInfo(newUserInfo);
      setLoaded(true);
    }
  }, []);

  useEffect(() => {
    const isChanged = !isEqual(userInfo, originUserInfo);
    setIsEdited(isChanged);
  }, [originUserInfo, userInfo]);

  const handleChange = (key, value) => {
    setUserInfo(prev => ({
      ...prev,
      [key]: value
    }));
  };


  const submiteEvent = async () => {
    if (state && isEdited) {
      if (isChangePassword && (userInfo.old_password === '' || userInfo.new_password === '')) { return message.error('旧密码和新密码都不能为空，或关闭修改密码再次保存'); }
      try {
        NProgress.start();
        let lastPercent = 0;
        const res = await axios.patch('/api/admin/users', userInfo, {
          withCredentials: true,
          onUploadProgress: (progressEvent) => {
            if (progressEvent.total) {
              const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
              if (percent !== lastPercent) {
                NProgress.set(percent / 100);
                lastPercent = percent;
              }
            }
          }
        });
        NProgress.done();
        const changeUser = res.data;
        if (changeUser.code === 0) {
          message.success(changeUser.codeMap?.[changeUser.code] || '更新成功');
          setUserInfo(prev => ({ ...prev, old_password: '', new_password: '' }));
          const uploadedUserInfo = { ...userInfo, old_password: undefined, new_password: undefined }
          localStorage.setItem(LOCAL_USER, JSON.stringify(uploadedUserInfo));
          setOriginUserInfo(uploadedUserInfo);
          eventBus.emit(EVENTBUS_USER_UPDATE, uploadedUserInfo);
          setState(false);
          setIsChangePassword(false);
        } else {
          message.error(changeUser.codeMap?.[changeUser.code] || '更新失败');
        }
      } catch (error) {
        NProgress.done();
        message.error('账号登录异常，请重新登录');
        router.push(ROUTE_LOGIN);
      }
    } else if (state && !isEdited) {
      setState(false);
      setIsChangePassword(false);
      setUserInfo({ ...originUserInfo });
    } else {
      setState(true);
    }
  };

  const resetEvent = () => {
    setUserInfo({ ...originUserInfo });
    setState(false);
    setIsChangePassword(false);
  }
  const changePasswordEvent = () => {
    if (isChangePassword) {
      setUserInfo(prev => ({ ...prev, old_password: '', new_password: '' }));
      setOriginUserInfo(prev => ({ ...prev, old_password: '', new_password: '' }));
    }
    setIsChangePassword(!isChangePassword);
  }

  const content = (
    <div>
      <PageTitle title="个人信息" buttonText={state && isEdited ? '保存' : state ? '关闭' : '编辑'} onButtonClick={submiteEvent} extraButtonText={state && isEdited ? '重置' : ''} onExtraButtonClick={resetEvent} />
      <form className='mb-2 bg-white rounded-sm px-4 py-1 mx-auto mt-2' onSubmit={e => e.preventDefault()}>
        <ImageUpload label={'头像'} state={state} value={userInfo?.avatar} handleChange={(value) => handleChange('avatar', value)} className={`w-20 h-20`}/>
        <SuperInput label="用户名" value={userInfo?.username} autoComplete={'username'} state={state} handleChange={(value) => handleChange('username', value)} />
        <SuperInput label="昵称" value={userInfo?.nickname} autoComplete={'nickname'} state={state} handleChange={(value) => handleChange('nickname', value)} />
        <SuperInput label="联系方式" value={userInfo?.mobile} autoComplete={'mobile'} state={state} handleChange={(value) => handleChange('mobile', value)} />
        <SuperInput label="邮箱" value={userInfo?.email} autoComplete={'email'} state={state} handleChange={(value) => handleChange('email', value)} />
        {state && (
          <label className="relative inline-flex items-center cursor-pointer select-none mr-4" style={{ minWidth: 48, height: 28 }}>
            <input type="checkbox" checked={isChangePassword} onChange={changePasswordEvent} className="sr-only peer" />
            <div className={` w-12 h-7 rounded-full transition-colors duration-200 ${isChangePassword ? 'bg-black shadow-none' : 'bg-white border border-gray-300 shadow-none'} peer-focus:ring-2 peer-focus:ring-black `} style={{ boxShadow: isChangePassword ? '0 2px 8px rgba(0,0,0,0.15)' : '0 2px 8px rgba(0,0,0,0.08)' }} > <div className={` absolute top-0.5 left-0.5 w-6 h-6 rounded-full bg-white transition-transform duration-200 shadow-none ${isChangePassword ? 'translate-x-5' : ''} `} style={{ transform: isChangePassword ? 'translateX(0px)' : 'translateX(0)', boxShadow: '0 1px 4px rgba(0,0,0,0.12)' }} /> </div>
            <span className="ml-3 text-sm text-gray-700">{isChangePassword ? '修改密码' : '不修改密码'}</span>
          </label>
        )}
        {isChangePassword && (
          <div>
            <SuperPasswordInput label='Old Password' value={''} autoComplete={'current-password'} state={state} handleChange={(value) => handleChange('old_password', value)} />
            <SuperPasswordInput label='New Password' value={''} autoComplete={'new-password'} state={state} handleChange={(value) => handleChange('new_password', value)} />
          </div>
        )}
      </form>
    </div>
  )

  return (
    <div>
      {loaded ? content : <Loading />}
    </div>
  )
}
